package com.sskj.givecoin.m.http;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.sskj.givecoin.m.bean.HttpData;
import com.sskj.givecoin.m.bean.bean.HttpResponse;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import okhttp3.ResponseBody;

/**
 * Created by lvzhihao on 17-7-4.
 */

public abstract class JsonConverter<T> extends AbsConverter<T> {

    @Override
    public T convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        String date = response.header("Date");
        SimpleDateFormat sf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
        Date parse = sf.parse(date);
        if (body == null) return null;
        T data = null;
        Gson gson = new Gson();
        JsonReader jsonReader = new JsonReader(body.charStream());
        Type genericSuperclass = getClass().getGenericSuperclass();
        Type type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
        data = gson.fromJson(jsonReader, type);
        int status;
        String msg;
        if (data instanceof HttpData) {
            status = ((HttpData) data).getStatus();
            msg = ((HttpData) data).getMsg();
        } else if (data instanceof HttpResponse) {
            status = ((HttpResponse) data).getCode();
            msg = ((HttpResponse) data).getMsg();
        } else if (data instanceof Map) {
            Map<String, String> map = (Map<String, String>) data;
            status = Integer.valueOf(map.get("status"));
            msg = map.get("msg");
        } else {
            status = -1;
            msg = "";
        }
        if (data.toString().contains("404") || status == 404) {//账户被冻结
            throw new LogoutException();
        }
        return data;
    }


}
